Tailwind CSS

Background Images


Tailwind CSS offers two main approaches to add background images.

 

1. Predefined Classes

 

Tailwind includes a set of utility classes prefixed with bg- that represent a few built-in background images like gradients. While these classes offer a quick solution, they might not always provide the specific image you need.

 

Example:

<div class="hero bg-gradient-to-r from-purple-500 to-pink-500">
 This is a hero section with a gradient background.
</div>

 

2. Custom Background Images

This method provides more flexibility for provinding your own images:

 

2.1 Arbitrary Values:

You can use square brackets [ ] to set a custom background image URL directly within a class.

<div class="bg-[url('/path/image.jpg')]">
 This element has a custom background image.
</div>

Note: Replace /path/image.jpg with the actual path to your image file.

 

2.2 Configuration and Class Reference:

For more maintainability and reusability, consider adding your image paths to the Tailwind configuration file (tailwind.config.js). Then, create a class referencing the image name.

 

Example:

// tailwind.config.js
module.exports = {
 content: [
   "./src/**/*.{js,jsx,ts,tsx}",
 ],
 theme: {
   extend: {
     backgroundImage: theme => ({
       'hero-pattern': "url('/image/hero-img-patt.jpg')",
     }),
   },
 },
 plugins: [],
};


Example:

<div class="bg-hero-pattern">
 This element uses a background image defined in the Tailwind config.
</div>